import type { Next, Context } from 'koa';
import { getAddress } from '../utils/ip';
import knex from '../utils/knex';
import type State from '../../typings/state';

/**
 * 用户操作日志
 * @param ctx
 * @param next
 */
export default async function (ctx: Context, next: Next) {
    const method = ctx.request.method;
    if (method === 'GET' || method === 'WEBSOCKET' || !ctx.user) {
        return next();
    }
    await next();
    const controller = ctx.controller;
    const action = ctx.action;
    const url = ctx.url;
    const params = ctx.request.body;
    const response = ctx.response.body as State;

    const errorNo = response.errno;
    let errorMsg;
    let status = '0';
    if (errorNo !== 0) {
        errorMsg = JSON.stringify(response.errmsg);
        status = '1';
    }
    // 获取ip和地址
    const addrInfo = await getAddress();
    // 组装日志对象
    const logData = {
        module: controller,
        url: url,
        method: method,
        method_name: action,
        params: JSON.stringify(params),
        response: JSON.stringify(response),
        oper_name: ctx.user.username,
        oper_ip: addrInfo.ip,
        oper_location: addrInfo.addr.split(' ')[0],
        status: status,
        error_msg: errorMsg,
        error_no: errorNo,
    };
    // 新增日志对象
    await knex('sys_log').insert(logData);
}
